import sys
from PySide2.QtWidgets import (QApplication, QMainWindow, QDialog, QMessageBox, 
                              QFrame, QLabel, QVBoxLayout, QPushButton)
from PySide2.QtCore import QDate, QTime, Qt, Signal
from PySide2.QtGui import QIcon

# 导入生成的UI文件
from Ui_main_window import Ui_MainWindow
from Ui_schedule_dialog import Ui_ScheduleDialog
from Ui_schedule_item import Ui_ScheduleItem  # 新增导入

class ScheduleItem(QFrame):
    deleteClicked = Signal(int)
    toggleClicked = Signal(int)
    
    def __init__(self, schedule_id, name, date, time, limit, repeat, enabled=True, parent=None):
        super().__init__(parent)
        self.ui = Ui_ScheduleItem()
        self.ui.setupUi(self)
        self.schedule_id = schedule_id
        self.enabled = enabled
        
        # 初始化UI数据
        self.ui.lblName.setText(name)
        self.ui.lblDate.setText(f"日期: {date}")
        self.ui.lblTime.setText(f"时间: {time}")
        self.ui.lblLimit.setText(f"每日上限: {limit}人")
        self.ui.lblRepeat.setText(f"重复: {self._get_repeat_text(repeat)}")
        self._update_status_ui()
        
        # 连接信号
        self.ui.btnDelete.clicked.connect(lambda: self.deleteClicked.emit(self.schedule_id))
        self.ui.btnToggle.clicked.connect(self._on_toggle_clicked)
        
        # 设置初始样式
        self.setStyleSheet("""
            ScheduleItem {
                border-left: 3px solid #4CAF50;
                background-color: #f8f9fa;
                padding: 8px;
                border-radius: 0 4px 4px 0;
                margin-bottom: 5px;
            }
            QPushButton {
                border: none;
                padding: 2px;
            }
        """)
    
    def _get_repeat_text(self, repeat):
        repeat_texts = {
            "daily": "每天",
            "weekdays": "工作日",
            "weekends": "周末",
            "once": "仅一次"
        }
        return repeat_texts.get(repeat, repeat)
    
    def _update_status_ui(self):
        self.ui.btnToggle.setIcon(QIcon.fromTheme(
            "media-playback-start" if self.enabled else "media-playback-stop"
        ))
        self.ui.lblStatus.setText("已启用" if self.enabled else "已禁用")
        self.ui.lblStatus.setStyleSheet(f"""
            padding: 2px 5px;
            border-radius: 3px;
            background-color: {'#d1fae5' if self.enabled else '#f3f4f6'};
            color: {'#065f46' if self.enabled else '#4b5563'};
        """)
    
    def _on_toggle_clicked(self):
        self.enabled = not self.enabled
        self._update_status_ui()
        self.toggleClicked.emit(self.schedule_id)

class ScheduleDialog(QDialog, Ui_ScheduleDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        
        # 初始化数据
        self.schedules = []
        
        # 设置默认值
        today = QDate.currentDate()
        self.dateEdit.setDate(today.addDays(1))  # 默认明天
        self.timeEdit.setTime(QTime.currentTime().addSecs(3600))  # 默认下一小时
        
        # 连接信号
        self.btnAddSchedule.clicked.connect(self.add_schedule)
        
        # 初始化无任务提示
        self.lblNoSchedules = QLabel("暂无定时任务\n点击上方'添加任务'按钮创建")
        self.lblNoSchedules.setAlignment(Qt.AlignCenter)
        self.verticalLayout_7.addWidget(self.lblNoSchedules)
        self.lblNoSchedules.setVisible(True)
    
    def add_schedule(self):
        # 获取输入值
        name = self.txtTaskName.text().strip() or f"定时任务 {len(self.schedules) + 1}"
        date = self.dateEdit.date().toString("yyyy-MM-dd")
        time = self.timeEdit.time().toString("hh:mm")
        limit = self.spinDailyLimit.value()
        repeat = ["daily", "weekdays", "weekends", "once"][self.comboRepeatMode.currentIndex()]
        
        # 检查时间冲突
        if self._has_time_conflict(date, time):
            QMessageBox.warning(self, "时间冲突", "该时间点已有定时任务，请选择其他时间")
            return
        
        # 创建新任务
        schedule_id = len(self.schedules) + 1
        schedule = {
            "id": schedule_id,
            "name": name,
            "date": date,
            "time": time,
            "limit": limit,
            "repeat": repeat,
            "enabled": True
        }
        
        self.schedules.append(schedule)
        self._update_schedule_list()
        
        # 重置表单
        self.txtTaskName.clear()
        self.txtTaskName.setPlaceholderText(f"定时任务 {len(self.schedules) + 1}")
    
    def _has_time_conflict(self, date, time, exclude_id=None):
        for schedule in self.schedules:
            if exclude_id and schedule["id"] == exclude_id:
                continue
            if schedule["date"] == date and schedule["time"] == time:
                return True
        return False
    
    def _update_schedule_list(self):
        # 确保无任务提示标签存在
        if not hasattr(self, 'lblNoSchedules') or not self.lblNoSchedules:
            self.lblNoSchedules = QLabel("暂无定时任务\n点击上方'添加任务'按钮创建")
            self.lblNoSchedules.setAlignment(Qt.AlignCenter)
            self.verticalLayout_7.addWidget(self.lblNoSchedules)
        
        # 清空现有布局（保留无任务提示标签）
        while self.verticalLayout_7.count() > 1:
            item = self.verticalLayout_7.takeAt(1)
            if item.widget():
                item.widget().deleteLater()
        
        # 如果没有任务，显示提示
        if not self.schedules:
            self.lblNoSchedules.setVisible(True)
            return
        
        self.lblNoSchedules.setVisible(False)
        
        # 添加所有任务项
        for schedule in self.schedules:
            item = ScheduleItem(
                schedule["id"],
                schedule["name"],
                schedule["date"],
                schedule["time"],
                schedule["limit"],
                schedule["repeat"],
                schedule["enabled"],
                self
            )
            item.deleteClicked.connect(self._delete_schedule)
            item.toggleClicked.connect(self._toggle_schedule)
            self.verticalLayout_7.addWidget(item)
        
        # 添加弹簧使内容顶部对齐
        self.verticalLayout_7.addStretch()
    
    def _delete_schedule(self, schedule_id):
        self.schedules = [s for s in self.schedules if s["id"] != schedule_id]
        self._update_schedule_list()
    
    def _toggle_schedule(self, schedule_id):
        for schedule in self.schedules:
            if schedule["id"] == schedule_id:
                schedule["enabled"] = not schedule["enabled"]
                break

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        
        # 连接按钮信号
        self.btnOpenScheduleDialog.clicked.connect(self._open_schedule_dialog)
    
    def _open_schedule_dialog(self):
        dialog = ScheduleDialog(self)
        dialog.exec_()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setStyle("Fusion")  # 设置现代UI风格
    
    window = MainWindow()
    window.show()
    
    sys.exit(app.exec_())